<template>
  <div>
    <el-select  @focus="setOptionWidth" popper-class="ft-org-select" :disabled="disabled"
               v-if="editable" v-model="orgInfo" value-key="orgId"
               :placeholder="placeholder" filterable
               @change="selectProject" :clearable="clearable"
               :popper-append-to-body="popperAppendToBody" >
      <el-option
       :style='{width: selectOptionWidth}'
          v-for="item in orgList"
          :key="item.orgInfo"
          :label="item.orgName"
          :value="item">
        <span>{{item.orgName}}</span>
      </el-option>
    </el-select>
    <span v-if="!editable&&orgInfo">{{orgInfo.orgName}}</span>
  </div>
</template>

<script>
export default {
  name: "FtOrgInfo",
  props: {
    placeholder: {
      type: String,
      default: '请输入组织机构名称'
    },
    value: {
      type: String
    },
    editable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    popperAppendToBody: {
      type: Boolean,
      default: true
    }
  },
  mounted() {
    this.request()
  },
  data() {
    return {
      selectOptionWidth:'',
      orgList: [],
      orgInfo: null,
      orgId: this.value
    }
  },
  methods: {
     setOptionWidth(event) {
          this.$nextTick(() =>{
              this.selectOptionWidth = event.srcElement.offsetWidth + 'px'            
          })
      },
    request() {
      this.loading = true
      let url = "/joys-rest/ncls-bms/contract/cascade/query"
      this.$http.get(url,{params: {parentId: null}}).then(resp => {
        this.orgList = resp.body
        this.merge()
        this.loading = false
      }).catch(err => {
        if(err.body) {
          this.$message.error(err.body.message || "组织机构查询失败！")
        } else {
          this.$message.error("组织机构查询失败！")
        }
        this.loading = false
      }).finally(() => {
        this.loading = false
      })
    },
    crearData(){
      this.orgInfo = {};
    },
    selectProject() {
      this.orgId = this.orgInfo.orgId
      this.$emit('input', this.orgInfo.orgId)
      this.$emit('change', this.orgInfo)
    },
    merge() {
      this.orgId && this.orgList.find((item) => {
        if (item.orgId === this.orgId) {
          this.orgInfo = item
        }
      })
    }
  },
  watch: {
    value(newVal) {
      this.orgId = newVal
      this.merge()
    }
  }
}
</script>

<style>
.ft-org-select .el-select-dropdown__item {
  padding: 4px 20px;
  font-size: 14px;
  line-height: 21px;
  height: auto;
}
</style>